/**
 * 工程名称:OMSJobExecutor
 * 文件名称:SysRefundServiceImpl.java
 * 所属包:cn.rkylin.oms.sysrefund.servcie.impl
 * 创建时间:2017年9月21日下午2:55:49
 * 创建人:zhanghao
 */

package cn.rkylin.oms.aftersale.sysrefund.servcie.impl;

import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.greenpineyu.fel.common.StringUtils;

import cn.rkylin.apollo.common.util.BeanUtils;
import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.sysrefund.dao.ISysRefundDAO;
import cn.rkylin.oms.aftersale.sysrefund.dao.ISysRefundSkuDAO;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefund;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefundSku;
import cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.aftersale.sysrefund.utils.QueryStatusParam;
import cn.rkylin.oms.aftersale.sysrefund.utils.dowloadsysrefund.SysRefundDownloader;
import cn.rkylin.oms.aftersale.sysrefund.utils.downloadecrefund.EcRefundDownloader;
import cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.aftersale.sysreturn.domain.SysReturnSku;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.base.refundReasonType.utils.RuleParseUtil;
import cn.rkylin.oms.base.refundReasonType.utils.apprhandler.ApprHandler;
import cn.rkylin.oms.common.base.AbstractAdapterFactory;
import cn.rkylin.oms.common.consts.ECRefundStatusConsts;
import cn.rkylin.oms.common.consts.StatusConsts;
import cn.rkylin.oms.common.consts.SysRefundStatusConsts;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.domain.OrderSku;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;

/**
 * 类名:SysRefundServiceImpl <br/>
 * 作用: 系统退款单服务层实现. <br/>
 * 创建原因: 对系统退款单提供对外实现. <br/>
 * 创建时间: 2017年9月21日 下午2:55:49 <br/>
 *
 * @author zhanghao
 * @version v1.0
 */
@Service("sysRefundService")
public class SysRefundServiceImpl extends ApolloService implements ISysRefundService {
    private static final String XVP_SHOP_TYPE = "小V铺";
    private static final String Kaola_SHOP_TYPE = "网易考拉";
    private static final Log logger = LogFactory.getLog(SysRefundServiceImpl.class);
    /**
     * sysRefundDAO:系统退款单数据访问层.
     */
    @Autowired
    private ISysRefundDAO sysRefundDAO;
    
    @Autowired
    private SnCodeExtractor snCodeExtractor;
    /**
     * sysRefundDAO:系统退款单数据访问层.
     */
    @Autowired
    private ISysRefundSkuDAO sysRefundSkuDAO;

    @Autowired
    private ProjectManagerService projectManagerService;

    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;
    /**
     * orderService:订单服务层.
     */
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDAO orderDAO;

    /**
     * 退款单自动下载.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#downloadEcRefundAuto(java.lang.String)
     */
    @Override
    public Object downloadEcRefundAuto(String shopId) throws Exception {
        return null;
    }

    /**
     * 退款单自动更新.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#updateEcRefundAuto(java.lang.String)
     */
    @Override
    public Object updateEcRefundAuto(String shopId) throws Exception {
        return null;
    }

    /**
     * 退款单条件查询.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#getSysRefundListByCondition(cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO)
     */
    @Override
    public List<SysRefundVO> getSysRefundListByCondition(SysRefundVO sysRefundVO) throws Exception {
        logger.info("开始根据查询条件获取数据");
        PageInfo<SysRefundVO> returnValueList = sysRefundDAO.pageSelectByCondition(0, 1, sysRefundVO);
        logger.info("根据查询条件获取数据完成");
        return returnValueList.getList();
    }

    /**
     * 根据退款单号和店铺ID下载退款单.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#downloadEcRefundByEcRefundCode(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public JSONObject downloadEcRefundByEcRefundCode(String shopId, String ecRefundCode) throws Exception {
    		Map<String, String> requestParam = new HashMap<String, String>();
        requestParam.put("shopId", shopId);
        requestParam.put("key", "ecRefundCode");
        requestParam.put("value", ecRefundCode);
        
        return downloadEcRefund(requestParam);
    }

    /**
     * downloadEcRefund:平台退款单手动下载. <br/>
     *
     * @author zhanghao
     * @param requestParam
     * 
     * @throws Exception
     */
    private JSONObject downloadEcRefund( Map<String, String> requestParam) throws Exception {
    	
    		/* 
    		 * 平台退款单手动下载：
    		 * 1. 从平台下载平台退款单
    		 * 2. 执行平台退款单进系统（新增或者更新）
    		 */
    		
    		EcRefundDownloader ecRefundDownloader = getEcRefundDownloader(requestParam);
    		JSONObject ecDownloadMessage = ecRefundDownloader.doDownloadEcRefund(requestParam);
    		
    		if("false".equalsIgnoreCase(ecDownloadMessage.getString("success"))||"failed".equalsIgnoreCase(ecDownloadMessage.getString("result"))) {
            return ecDownloadMessage;
        }
    		
    		SysRefundDownloader sysRefundDownloader = getSysRefundDownloader(requestParam);
    		JSONObject sysDownloadMessage = sysRefundDownloader.doDownloadSysRefund(requestParam);
    		
        return sysDownloadMessage;
    }

    private SysRefundDownloader getSysRefundDownloader(Map<String, String> requestParam) {
    	EcRefundDownloader returnValue;
		return BeanUtils.getBean("defaultSysRefundDownloader");
	}

	private EcRefundDownloader getEcRefundDownloader(Map<String, String> requestParam) {
		EcRefundDownloader returnValue;
		
		ShopVO shopVO = AbstractAdapterFactory.getShop(requestParam.get("shopId"));
		
		if(XVP_SHOP_TYPE.equals(shopVO.getShopType())){
			returnValue = BeanUtils.getBean("xvpEcRefundDownloader");
		}else if(Kaola_SHOP_TYPE.equals(shopVO.getShopType())){
            returnValue = BeanUtils.getBean("kaolaEcRefundDownloader");
        }else {
			returnValue = BeanUtils.getBean("defaultEcRefundDownloader");
		}
    		return returnValue;
	}

	/**
     * 根据店铺ID和客户ID下载退款单.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#downloadEcRefundByCustomerId(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public JSONObject downloadEcRefundByCustomerId(String shopId, String customerId) throws Exception {
        Map<String, String> requestParam = new HashMap<String, String>();
        requestParam.put("shopId", shopId);
        requestParam.put("key", "customerId");
        requestParam.put("value", URLEncoder.encode(customerId,"UTF-8"));
        
        return downloadEcRefund(requestParam);
    }
    
    /**
     * 根据店铺ID和订单编号下载退款单.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#downloadEcRefundByCustomerId(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public JSONObject downloadEcRefundByOrderCode(String shopId, String orderCode) throws Exception {
    	Map<String, String> requestParam = new HashMap<String, String>();
        requestParam.put("shopId", shopId);
        requestParam.put("key", "orderCode");
        requestParam.put("value", orderCode);
        
        return downloadEcRefund(requestParam);
    }

    /**
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#getSysRefundListByCondition(int,
     *      int, cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO)
     */
    @Override
    public PageInfo<SysRefundVO> getSysRefundListByCondition(int page, int length, SysRefundVO queryParamVO) throws Exception {
        PageInfo<SysRefundVO> returnValue = null;
        logger.info("开始执行退款单查询...");
        try {
            if (StringUtils.isNotEmpty(queryParamVO.getQueryStatus())) {
                modifyQueryParamVO(queryParamVO.getQueryStatus(), queryParamVO);
            }

            returnValue = sysRefundDAO.pageSelectByCondition(page, length, queryParamVO);
            logger.info("开始执行退款单查询...");
        } catch (Exception e) {
            logger.info("执行退款单查询出现错误".concat(e.getMessage()));
            throw e;
        }
        return returnValue;
    }

    /**
     * modifyQueryParamVO:根据查询状态构造系统退款单查询条件.详细为： <br/>
     * .<br/>
     *
     * @author zhanghao
     * @param queryParamVO
     */
    private void modifyQueryParamVO(String queryStatus, SysRefundVO queryParamVO) {
        try {
            if (QueryStatusParam.getMaps().containsKey(queryStatus)) {
                Method methodName = QueryStatusParam.getMaps().get(queryStatus);
                queryParamVO = (SysRefundVO) methodName.invoke(new QueryStatusParam(), queryParamVO);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 获取系统退款单的各个状态.
     * 
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#findStateCount(SysRefundVO queryParamVO)
     */
    @Override
    public List<HashMap> findStateCount(SysRefundVO queryParamVO) throws Exception {
        List<HashMap> returnMap = sysRefundDAO.selectStateCount(queryParamVO);
        return returnMap;
    }

    /**
     * 废弃系统退款单.
     * 
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#cancelSysRefunds(java.lang.String[])
     */
    @Override
    public int cancelSysRefunds(String[] refundIdArray) throws Exception {
        int iRes = 0;
        Date now = new Date();
        SysRefundVO param = new SysRefundVO();
        List refundIdArrayList = new ArrayList();
        Collections.addAll(refundIdArrayList, refundIdArray);
        param.setPrimariyKeyList(refundIdArrayList);
        /**** 2020-04-26 ****/
        // param.setDeleted(YesNoConst.YES);
        param.setRefundStatus("c");
        /*******************/
        param.setUpdateTime(now);
        iRes = sysRefundDAO.updateByPrimaryKeySelective(param);
        if (iRes > 0){
            //更新系统订单退款单的状态
            OrderVO orderVOUpdate = new OrderVO();
            //通过退款单id获取订单id
            SysRefund sysRefundForOne = sysRefundDAO.selectByPrimaryKey(refundIdArrayList.get(0).toString());
            if (sysRefundForOne != null) {
                String strSourceId = sysRefundForOne.getOrderId();
                if(org.apache.commons.lang.StringUtils.isNotBlank(strSourceId)){
                    //通过来源id获取未废弃退款单信息
                    List<SysRefund> SysRefundByOrderID = sysRefundDAO.selectSysRefundByOrderID(strSourceId);
                    if (SysRefundByOrderID == null || SysRefundByOrderID.size()<=0){
                        //没有 未废弃的退款单，更新订单退款单标识为 n
                        orderVOUpdate.setOrderId(strSourceId);
                        orderVOUpdate.setHasRefund("n");
                        int iOrderUpdate = orderDAO.update(orderVOUpdate);
                    }
                }
            }
        }
        return iRes;
    }

    /**
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#getSysRefundListById(java.lang.String)
     */
    @Override
    public SysRefund getSysRefundListById(String sysRefundId) throws Exception {
        SysRefund returnValue = sysRefundDAO.selectByPrimaryKey(sysRefundId);
        return returnValue;
    }

    /**
     * 保存退款单及其明细.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#saveSysRefunds(cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO)
     */
    @Override
    @Transactional
    public int saveSysRefunds(SysRefundVO sysRefundVO) throws Exception {
        int returnValue = 0;
        String sysOrderId = sysRefundVO.getOrderId();

        OrderVO order = new OrderVO();
        order.setOrderId(sysOrderId);
        PageInfo<OrderVO> orderList = orderService.findByWhere(0, Integer.MAX_VALUE, order);
        if (orderList.getSize() > 0) {
            order = orderList.getList().get(0);
        }

        Date now = new Date();
        if (StringUtils.isEmpty(sysRefundVO.getRefundId())) {
            String refundId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            String ecRefundCode = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            String sysRefundCode = generateRefundCode(order.getShopId());
            // 新增退款单
            sysRefundVO.setRefundId(refundId);
            sysRefundVO.setRefundCode(sysRefundCode);

            sysRefundVO.setDeleted(YesNoConst.NO);
            sysRefundVO.setCreateTime(now);
            sysRefundVO.setUpdateTime(now);
            sysRefundVO.setRefundStatus(StatusConsts.AWAIT);
            sysRefundVO.setEntId(order.getEntId());
            sysRefundVO.setOrderCode(order.getOrderCode());
            sysRefundVO.setIsAutoCreate(YesNoConst.NO);
            sysRefundVO.setEcRefundCode(ecRefundCode);
            if (YesNoConst.YES.equalsIgnoreCase(sysRefundVO.getHasGoodReturn())) {
                sysRefundVO.setEcRefundStatus(ECRefundStatusConsts.EC_WAIT_SELLER_CONFIRM_GOODS);
            } else {
                sysRefundVO.setEcRefundStatus(ECRefundStatusConsts.EC_WAIT_SELLER_AGREE);
            }
            sysRefundVO.setPrjId(order.getPrjId());
            sysRefundVO.setRefundCreateTime(now);
//            sysRefundVO.setRefundTime(now);
            int iRes = sysRefundDAO.insert(sysRefundVO);
            if (iRes > 0){
                //更新系统订单退款单的状态
                OrderVO orderVOUpdate = new OrderVO();
                orderVOUpdate.setOrderId(sysOrderId);
                orderVOUpdate.setHasRefund("y");
                int iOrderUpdate = orderDAO.update(orderVOUpdate);
            }

            // 新增退款单明细
            SysRefundSku refundSku = null;
            for(int i=0,j=sysRefundVO.getSysRefundSkuList().size();i<j;i++){
                refundSku = sysRefundVO.getSysRefundSkuList().get(i);
                refundSku.setRefundSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                refundSku.setRefundId(refundId);
                sysRefundSkuDAO.insert(sysRefundVO.getSysRefundSkuList().get(i));
            }

            returnValue = iRes;
        } else {
            String refundId = sysRefundVO.getRefundId();
            // 更新退款单
            sysRefundVO.setUpdateTime(now);
            sysRefundVO.setDeleted(YesNoConst.NO);
            returnValue = sysRefundDAO.updateByPrimaryKeySelective(sysRefundVO);

            // 删除已有的退款单明细
            SysRefundSku record = new SysRefundSku();
            record.setRefundId(refundId);
            record.setDeleted(YesNoConst.YES);
            sysRefundSkuDAO.updateByRefundIdSelective(record);

            // 新增退款单明细
            SysRefundSku refundSku = null;
            for(int i=0,j=sysRefundVO.getSysRefundSkuList().size();i<j;i++){
                refundSku = sysRefundVO.getSysRefundSkuList().get(i);
                refundSku.setRefundSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                refundSku.setRefundId(refundId);
                sysRefundSkuDAO.insert(sysRefundVO.getSysRefundSkuList().get(i));
            }
        }

        return returnValue;
    }

    /**
     * generateRefundCode:根据店铺ID生成系统退款单编码. <br/>
     *
     * @author zhanghao
     * @param shopId
     * @return
     * @throws Exception
     */
    private String generateRefundCode(String shopId) throws Exception {
        return generateReturnCodeWithType("RF", shopId);
    }

    /**
     * generateReturnCodeWithType:编码生成方法 <br/>
     *
     * @author zhanghao
     * @param codeType
     *            编码类型
     * @param shopId
     *            店铺ID
     * @return
     * @throws Exception
     */
    private String generateReturnCodeWithType(String codeType, String shopId) throws Exception {
        ShopVO shop = shopService.getShopById(shopId);
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        ProjectVO project = projectManagerService.findProjectById(shop.getPrjId());
        String prjShortName = project.getPrjShortName();
        String returnCode = codeType + prjShortName + CodeUtil.getCode();
        return returnCode;
    }

    @Override
    public List<SysRefund> findSysRefundList(Map<String, String> map) throws Exception {
        SysRefund sysRefund = new SysRefund();
        sysRefund.setOrderId(map.get("orderId"));
        sysRefund.setIsCancel(map.get("isCancel"));
        sysRefund.setDeleted(map.get("deleted"));
        return sysRefundDAO.findSysRefundList(sysRefund);
    }

    /**
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#getSysRefundDetailById(java.lang.String)
     */
    @Override
    public SysRefundVO getSysRefundDetailById(String sysRefundId) throws Exception {
        SysRefundVO returnValue = sysRefundDAO.selectDetailByPrimaryKey(sysRefundId);
        
        // 设置商品的序列号
        List<OrderSku> orderSkuList = returnValue.getOrderSkuList();
        
        // 为退货商品增加sn号
        List<SysReturnSku> returnSkuList = returnValue.getSysReturnSkuList4Detail();
        for (SysReturnSku sysReturnSku : returnSkuList) {
            String snCode = snCodeExtractor.getSnCodeByReturnSkuId(sysReturnSku.getReturnSkuId());
            sysReturnSku.setSn(snCode);
        }
        return returnValue;
    }

    /**
     * 审核退款单,返回审核结果
     *
     */
    @Override
    public JSONObject doAppr(String sysRefundId) throws Exception {
        SysRefundVO sysRefundVO = sysRefundDAO.selectDetailByPrimaryKey(sysRefundId);
        JSONObject apprResult = ApproveSysRefundWithReason(sysRefundVO, false);
        apprResult.put("sysRefundCode", sysRefundVO.getRefundCode());
        apprResult.put("sysRefundId", sysRefundVO.getRefundId());
        return apprResult;
    }

    /**
     * 审核退款单,返回审核结果
     *
     */
    @Override
    public String doForceAppr(String sysRefundId) throws Exception {
        String returnString = "";
        // SysRefundVO sysRefundVO =
        // sysRefundDAO.selectDetailByPrimaryKey(sysRefundId);

        // 3. 执行审核
        apprSysRefundSuccess(sysRefundId);

        // 4. 对于有退货诉求但关联订单在系统中没有未废弃的退货单，提示是否自动创建退货单。
        // if (YesNoConst.YES.equalsIgnoreCase(sysRefundVO.getHasGoodReturn()))
        // {
        // List<SysReturnVO> returnList = sysRefundVO.getSysReturnVOList();
        // boolean hasUnCanceledReturn = false;
        // for (SysReturnVO sysReturnVO : returnList) {
        // if (!YesNoConst.YES.equalsIgnoreCase(sysReturnVO.getIsCancel())) {
        // hasUnCanceledReturn = true;
        // }
        // }
        //
        // if (!hasUnCanceledReturn) {
        // returnString = "是否自动创建退货单";
        // }
        // }

        return returnString;
    }

    /**
     * doForceApprValid:强制审核. <br/>
     *
     * @author zhanghao
     * @param sysRefundId
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject doForceApprValid(String sysRefundId) throws Exception {
        SysRefundVO sysRefundVO = sysRefundDAO.selectDetailByPrimaryKey(sysRefundId);
        JSONObject apprResult = ApproveSysRefundWithReason(sysRefundVO, true);
        apprResult.put("sysRefundCode", sysRefundVO.getRefundCode());
        apprResult.put("sysRefundId", sysRefundVO.getRefundId());
        return apprResult;
    }

    /**
     * ApproveSysRefundWithReason:根据退款原因的设置审核退款单. <br/>
     *
     * @author zhanghao
     * @param sysRefundVO
     * @param isForce
     * @return
     * @throws Exception
     */
    private JSONObject ApproveSysRefundWithReason(SysRefundVO sysRefundVO, boolean isForce) throws Exception {
        /*
         * 本方法的逻辑如下： <br/> 1. 根据apprRule构造责任链 <br/> 2. 将sysRefundVO传入责任链，并执行相关校验
         * <br/> 3. 返回结果 <br/>
         */
        ApprHandler apprHandler = null;
        if (isForce) {
            apprHandler = RuleParseUtil.getForceApprHandler();
        } else {
            apprHandler = RuleParseUtil.getApprHandler();
        }
        apprHandler.HandleRequest(sysRefundVO, null);
        return apprHandler.getContextObj().getJSONObject("result");
    }

    /**
     * apprSysRefundSuccess:审核同意. <br/>
     *
     * @author zhanghao
     * @return
     * @throws Exception
     */
    private int apprSysRefundSuccess(String sysRefundId) throws Exception {
        Date now = new Date();
        SysRefundVO sysRefund = new SysRefundVO();
        sysRefund.setRefundId(sysRefundId);
        sysRefund.setApprTime(now);
        sysRefund.setUpdateTime(now);
        sysRefund.setRefundStatus(SysRefundStatusConsts.AUTHENTICATED);
        return sysRefundDAO.updateByPrimaryKeySelective(sysRefund);
    }

    /**
     * apprSysRefundFailed:审核拒绝. <br/>
     *
     * @author zhanghao
     */
    private void apprSysRefundFailed(String sysRefundId) {
        // 不做操作
    }

    /**
     * 退款单取消审核.
     * 
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#doCancelAppr(java.lang.String[])
     */
    @Override
    public int doCancelAppr(String[] refundIdArray) throws Exception {
        int returnValue = 0;
        Date now = new Date();
        SysRefundVO sysRefund = new SysRefundVO();
        sysRefund.setPrimariyKeyList(Arrays.asList(refundIdArray));
        sysRefund.setUpdateTime(now);
        sysRefund.setApprTime(null);
        sysRefund.setRefundStatus(SysRefundStatusConsts.REGISTER);
        returnValue = sysRefundDAO.updateByPrimaryKeySelective(sysRefund);
        return returnValue;
    }

    /**
     * 执行退款.
     * 
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#doRefund(java.lang.String[])
     */
    @Override
    public int doRefund(String[] refundIdArray) throws Exception {
        int returnValue = 0;
        Date now = new Date();
        SysRefundVO sysRefund = new SysRefundVO();
        sysRefund.setPrimariyKeyList(Arrays.asList(refundIdArray));
        sysRefund.setUpdateTime(now);
        sysRefund.setRefundTime(now);
        sysRefund.setRefundStatus(SysRefundStatusConsts.REFUNDED);
        returnValue = sysRefundDAO.updateByPrimaryKeySelective(sysRefund);
        return returnValue;
    }

    /**
     * 退款校验逻辑：如果仅退款不退货，给出提示；如果既退款又退货，且退款单所属订单关联有未完成且未废弃的退货单时，也给出提示信息。
     * 
     * @throws Exception
     * @see cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService#doRefundValid(java.lang.String)
     */
    @Override
    public String doRefundValid(String refundId) throws Exception {
        String returnMessage = "";
        SysRefundVO sysRefundVO = getSysRefundDetailById(refundId);
        if (YesNoConst.NO.equalsIgnoreCase(sysRefundVO.getHasGoodReturn())) {
            returnMessage = "仅退款不退货";
        } else {
            List<SysReturnVO> sysReturnVOList = sysRefundVO.getSysReturnVOList();
            for (SysReturnVO sysReturnVO : sysReturnVOList) {
                // 校验退款单对应的退货单是否未废弃且未完成
                if (!"z".equalsIgnoreCase(sysReturnVO.getReturnStatus()) && YesNoConst.NO.equalsIgnoreCase(sysReturnVO.getIsCancel())) {
                    returnMessage = "存在未废弃且未完成的退货单【单号：" + sysReturnVO.getReturnCode() + "】";
                    break;
                }

            }
        }
        return returnMessage;
    }

    /**
     * 通过订单ID获取退款单基本信息 wangxing add
     * 
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public List<SysRefund> findSysRefundListByOrderId(String orderId) throws Exception {
        SysRefund sysRefund = new SysRefund();
        sysRefund.setOrderId(orderId);
        sysRefund.setDeleted("n");
        return sysRefundDAO.findSysRefundList(sysRefund);
    }
    
    @Override
    public int selectCount(Map<String, Object> params) throws Exception {
        return sysRefundDAO.selectCount(params);
    }

    @Override
    public int getUnGoingCount(Map<String, String> paramMap) throws Exception {
        return sysRefundDAO.getUnGoingCount(paramMap);
    }
}
